package com.myFwk.config.redis.redisson;

import lombok.extern.slf4j.Slf4j;
import org.mvel2.Unit;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Title: 分布式锁工具
 * @Description: 创建分布式锁接口工具类，便于扩展对其工具类京
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/10/18
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
@Component
@Slf4j
public class DistributedLocker {
    @Autowired
    private RedissonClient redissonClient;


    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * 对其锁设置超时时间
     *
     * @param lockKey
     * @param timeout
     * @return
     */
    public RLock lock(String lockKey, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * @param lockKey
     * @param unit
     * @param waitTime  等待获取锁的时间
     * @param leaseTime 获取锁之后持有锁的时间 租赁时间
     * @return
     */
    public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("lock.tryLock() error:{}", e.getMessage());
            return false;
        }
        return true;


    }

    /**
     * 释放锁
     *
     * @param lockKey
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    public void unlock(RLock lock) {
        if (lock != null) {
            lock.unlock();
        }

    }

}
